<?php

class Core_Controller_Action extends Zend_Controller_Action {
    
    public function init() {
        parent::init();
        $session = Zend_Registry::get("session");
        $this->view->session = $session;
        $this->session = $session;
        
        $this->view->controller = $this->_getParam("controller");
    }
    
    public function preDispatch() {
        parent::preDispatch();
        if (!$this->isAllowed()) {
            $this->redirect("/auth");
        }
    }

    protected function setAjaxCall() {
        $this->_helper->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
    }
    
    protected function isPost() {
        return $this->getRequest()->isPost();
    }
    
    public function isAllowed() {
        if (!empty($this->session->user)) {
            $role = $this->session->user->role;
        } else {
            $role = Core_Role::ROLE_GUEST;
        }
        $acl = Zend_Registry::get("acl");
        $resource = "{$this->_getParam("module")}:{$this->_getParam("controller")}";
        if ($acl->has($resource)) {
            return $acl->isAllowed($role, $resource, $this->_getParam("action"));
        } else {
            return true;
        }
        
    }
    
    protected function uploadFile($field_name, $des = NULL) {
        if (!empty($_FILES[$field_name]['name'])) {
            $file = $_FILES[$field_name]['name'];
            $splitted_dot = explode('.', $file);
            $file_extension = end($splitted_dot);
            $file_wt_ext = str_replace(".$file_extension", "", $file);
            $new_file_name = $file_wt_ext . time() . ".$file_extension";
            if ( empty($des) ) {
                move_uploaded_file($_FILES[$field_name]['tmp_name'], UPLOAD_PATH . $new_file_name);
                return $new_file_name;
            }
            else {
                $des .= DIRECTORY_SEPARATOR . $new_file_name;
                move_uploaded_file($_FILES[$field_name]['tmp_name'], $des);   
                return str_replace(UPLOAD_PATH, "", $des);
            }
        } else {
            return NULL;
        }
    }
    
    protected function _handlePageNotFound() {
        $url = $this->view->url(array(
            'action' => 'page-not-found',
            'controller' => 'error',
            'module' => 'default'
        ), NULL, true);
        $full_url = $this->view->serverUrl($url);
        $this->redirect($full_url);
        return;
    }
    
    
    protected function _getTimestampParam($field_name) {
        $value = $this->_getParam($field_name);
        if (!empty($value)) {
            $time = Datetime::createFromFormat("!d/m/Y", $value);
            return $time->getTimestamp();
        }
        return NULL;
    }
}

?>
